package com.money.tracker.common.helper;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * <p>
 * 查询优化工具类
 * <p>
 *
 * @author zhangshuai
 * &#064;@date 2024/09/22
 */
@Component
@SuppressWarnings(value = {"unchecked"})
@RequiredArgsConstructor
public class QueryCacheHelper {
    private final RedisHelper redisHelper;

    /**
     * 优先查询redis，redis如果存在，那么直接返回，不存在那么查询数据库
     *
     * @param key
     * @param databaseQuery
     * @return {@link T }
     */

    public <T> T queryWithCache(String key, Supplier<T> databaseQuery) {
        if (redisHelper.hasKey(key)) {
            return redisHelper.getCacheObject(key);
        }
        T t = databaseQuery.get();
        redisHelper.setCacheObject(key, t);
        return t;
    }

    /**
     * @param key
     * @param timeout
     * @param timeUnit
     * @param databaseQuery
     * @return {@link T }
     */

    public <T> T queryWithCache(String key, Integer timeout, TimeUnit timeUnit, Supplier<T> databaseQuery) {
        if (redisHelper.hasKey(key)) {
            return redisHelper.getCacheObject(key);
        }
        T t = databaseQuery.get();
        redisHelper.setCacheObject(key, t, timeout, timeUnit);
        return t;
    }

}
